let db = require('../db/index')


// 注册
exports.signUp = (req, res) => {
  const info = req.body
  const sql = 'insert into userInfo (username,email,password,avatar) values (?,?,?,?)'
  db.query(sql, [info.username, info.email, info.password,info.avatar], (err, data) => {
    if (err) {
      return res.send({
        code: 10000,
        message:'添加失败' + '，此邮箱已被注册'
      })
    }
    res.send({
      code: 20000,
      data: '添加成功'
    })
  })
}

// 登录
exports.signIn = (req, res) => {
  const info = req.body
  const sql = 'select * from userInfo where email = ? and password = ?'
  db.query(sql, [info.email, info.password], (err, data) => {
    if (err) {
      return res.send({
        code: 10000,
        message:'登录失败'
      })
    }
    if (data.length === 0) {
      return res.send({
        code: 10000,
        message:'就汰死，密码都记不对~~真废'
      })
    }
    let result = {}
    for(let key in data[0]){
      if(key !== 'password'){
        result[key] = data[0][key]
      }
    }

    res.send({
      code: 20000,
      data: result
    })
  })
}

// 升级权限
exports.upUserInfo = (req, res) => {
  const id = req.body.id
  const sql = 'update userInfo set permission = 1 where id = ?'
  db.query(sql, id, (err, data) => {
    if(err){
      return res.send('升级失败' + err.message)
    }
    res.send({
      code: 20000,
      data: '升级成功'
    })
  })
}

// 获取用户信息
exports.getUserInfo = (req, res) => {
  const email = req.query.email
  const sql = 'select * from userInfo where email = ?'
  db.query(sql, email, (err, data) => {
    if(err){
      return res.send('获取失败' + err.message)
    }
    if(data.length === 0){
      return res.send('获取失败，此邮箱未注册')
    }
    res.send({
      code: 20000,
      data: data[0]
    })
  })
}

// 重置密码
exports.resetPassword = (req, res) => {
  const id = req.query.id
  const sql = 'update userInfo set password = 123456 where id = ?'
  db.query(sql, id, (err, data) => {
    if(err){
      return res.send('重置失败' + err.message)
    }
    res.send({
      code: 20000,
      data: '重置成功'
    })
  })
}

// 拉黑用户
exports.blackUser = (req, res) => {
  const id = req.query.id
  const sql = 'update userInfo set permission = 3 where id = ?'
  db.query(sql, id, (err, data) => {
    if(err){
      return res.send('拉黑失败' + err.message)
    }
    res.send({
      code: 20000,
      data: '拉黑成功'
    })
  })
}